package com.hhf.springboot.utils;

import lombok.SneakyThrows;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author hhf
 * @Date 2025/1/11
 * @Description 日期工具类
 */
public class DateUtils {

    private static final String INIT_DATE = "1970-01-01 08:00:00";
    private static final DateFormat DEFAULT_DF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final String FMT_YMD = "yyyy-MM-dd";

    public static Date getNow() {
        return new Date();
    }

    public static String format(Date date) {
        return DEFAULT_DF.format(date);
    }

    public static String format(Date date, String fmt) {
        return new SimpleDateFormat(fmt).format(date);
    }

    public static Date dayAfter(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days);
        return cal.getTime();
    }

    public static Date getZeroDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    @SneakyThrows
    public static Date parse(String dateStr, String fmt) {
        return new SimpleDateFormat(fmt).parse(dateStr);
    }


    @SneakyThrows
    public static Date parse(String dateStr) {
        return DEFAULT_DF.parse(dateStr);
    }

    @SneakyThrows
    public static Date getInitDate() {
        return DEFAULT_DF.parse(INIT_DATE);
    }

    /**
     * 计算两个日期相差天数
     *
     * @param beginDay 开始日期
     * @param endDay   结束日期
     * @return 相差天数
     */
    public static int diffDay(Date beginDay, Date endDay) {
        long time = Math.abs(endDay.getTime() - beginDay.getTime());
        return (int) (time / 1000 / 60 / 60 / 24);
    }
}
